empty=
ifneq ($(ComSpec),)
MV=cmd /c move
RM=del
DIRSEP=\$(empty)
EXESUFFIX=.exe
CGISUFFIX=.exe
else
MV=mv
RM=rm
DIRSEP=/
EXESUFFIX=
CGISUFFIX=.cgi
endif

.PHONY: clean test

CASTLING_DIR=../../../source
BUILDDIR=build

OCAMLCFLAG=-g -w L -I $(BUILDDIR)

tinypascal$(CGISUFFIX): \
		$(BUILDDIR)/lexical.cmx $(BUILDDIR)/scanner.cmx $(BUILDDIR)/parser.cmx $(BUILDDIR)/web.cmx $(BUILDDIR)/main.cmx
	ocamlopt.opt -o $@ $(OCAMLCFLAG) unix.cmxa $+

$(BUILDDIR)/main.cmx $(BUILDDIR)/main.cmi: main.ml \
		$(BUILDDIR)/lexical.cmx $(BUILDDIR)/scanner.cmx $(BUILDDIR)/parser.cmx $(BUILDDIR)/web.cmx
	ocamlopt.opt -c -o $@ $(OCAMLCFLAG) $<

ifneq ($(EXESUFFIX),)
test: test$(EXESUFFIX)
endif

test$(EXESUFFIX): \
		$(BUILDDIR)/lexical.cmx $(BUILDDIR)/scanner.cmx $(BUILDDIR)/parser.cmx $(BUILDDIR)/test.cmx
	ocamlopt.opt -o $@ $(OCAMLCFLAG) $+

$(BUILDDIR)/test.cmx $(BUILDDIR)/test.cmi: test.ml \
		$(BUILDDIR)/lexical.cmx $(BUILDDIR)/scanner.cmx $(BUILDDIR)/parser.cmx
	ocamlopt.opt -c -o $@ $(OCAMLCFLAG) $<

$(BUILDDIR)/scanner.cmx $(BUILDDIR)/scanner.cmi: scanner.ml $(BUILDDIR)/lexical.cmi
	ocamlopt.opt -c -o $@ $(OCAMLCFLAG) $<

$(BUILDDIR)/parser.cmx $(BUILDDIR)/parser.cmi: parser.ml $(BUILDDIR)/lexical.cmi
	ocamlopt.opt -c -o $@ $(OCAMLCFLAG) $<

parser.ml: $(BUILDDIR)/syntax.exe
	set OCAMLRUNPARAM=b && $(BUILDDIR)$(DIRSEP)syntax.exe > $(BUILDDIR)$(DIRSEP)parser.tmp.ml
	$(MV) $(BUILDDIR)$(DIRSEP)parser.tmp.ml parser.ml

$(BUILDDIR)/syntax.exe: \
		$(BUILDDIR)/lalr1.cmx $(BUILDDIR)/castling.cmx $(BUILDDIR)/lexical.cmx $(BUILDDIR)/syntax.cmx
	ocamlopt.opt -o $@ $(OCAMLCFLAG) $+

$(BUILDDIR)/syntax.cmx $(BUILDDIR)/syntax.cmi: syntax.ml \
		$(BUILDDIR)/lalr1.cmx $(BUILDDIR)/castling.cmx $(BUILDDIR)/lexical.cmx
	ocamlopt.opt -c -o $@ $(OCAMLCFLAG) $<

$(BUILDDIR)/lexical.cmx $(BUILDDIR)/lexical.cmi: lexical.ml $(BUILDDIR)
	ocamlopt.opt -c -o $@ $(OCAMLCFLAG) $<

$(BUILDDIR)/castling.cmx $(BUILDDIR)/castling.cmi: $(CASTLING_DIR)/castling.ml $(BUILDDIR)/lalr1.cmi
	ocamlopt.opt -c -o $@ $(OCAMLCFLAG) $<

$(BUILDDIR)/lalr1.cmx $(BUILDDIR)/lalr1.cmi: $(CASTLING_DIR)/lalr1.ml
	ocamlopt.opt -c -o $@ $(OCAMLCFLAG) $<

$(BUILDDIR)/web.cmx web.cmi: ../web.ml $(BUILDDIR)
	ocamlopt.opt -c -o $@ $(OCAMLCFLAG) $<

$(BUILDDIR):
	mkdir $(BUILDDIR)

clean:
	-$(RM) tinypascal$(CGISUFFIX) test$(EXESUFFIX) parser.ml
	-$(RM) $(BUILDDIR)$(DIRSEP)*.cm? $(BUILDDIR)$(DIRSEP)*.o $(BUILDDIR)$(DIRSEP)parser.tmp.ml $(BUILDDIR)$(DIRSEP)syntax.exe
	-rmdir $(BUILDDIR)
